<!-- 员工模块主页 -->
<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ pageObj.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import?type=user')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button :disabled="!checkPermission('POINT-USER-ADD')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="">
            <template v-slot="obj">
              {{ (pageObj.page - 1) * pageObj.size + obj.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center">
            <template v-slot="{ row }">
              <img
                slot="reference"
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                class="avator"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry" align="center">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState" align="center">
            <template v-slot="{ row }">
              <!-- 根据当前状态来确定是否打开开关 -->
              <el-switch v-model="row.enableState" :active-value="1" :inactive-value="0" disabled />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button :disabled="!checkPermission('POINT-USER-UPDATE')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button :disabled="!checkPermission('point-user-delete')" type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="pageObj.size"
            :current-page="pageObj.page"
            :total="pageObj.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <add-employee :show-dialog.sync="showDialog" @tolastpage="addEmployeeToPage" />
    </div>
    <el-dialog title="二维码" :visible.sync="showCodeDialog" @close="imgUrl=''">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <assignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import addEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import assignRole from './components/assign-role.vue'

export default {
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      // 控制进度条显示隐藏的变量
      loading: false,
      // 接收员工列表数据的数组
      employeeList: [],
      // 分页对象
      pageObj: {
        page: 1,
        size: 10,
        total: 0
      },
      showDialog: false,
      showCodeDialog: false,
      // 用户id
      userId: '',
      // 控制分配员工角色弹窗显示或隐藏的变量
      showRoleDialog: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.pageObj)
      this.employeeList = rows.map(item => {
        return {
          ...item,
          // 如果获取到的数据中没有enableState，就用随机数生成来测试一下效果
          enableState: item.enableState || Math.round(Math.random())
        }
      })
      console.log('员工列表数据', this.employeeList)
      this.pageObj.total = total
      this.loading = false
    },
    changePage(newPage) {
      this.pageObj.page = newPage
      // 改变页码后，重新获取对应页码的员工列表数据进行渲染
      this.getEmployeeList()
    },
    // element的table组件自带的功能
    formatEmployment(row, column, cellValue, index) {
      // 枚举数据
      // console.log(cellValue)
      // console.log(1)
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async deleteEmployee(id) {
      await this.$confirm('确定要删除该员工吗?')
      await delEmployee(id)
      this.getEmployeeList()
      this.$message.success('删除员工成功!')
    },
    // 导出excel功能
    exportData() {
      // 表头对应关系，将中文与英文对应
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // js-xlsx体积较大，导出功能也不常用，使用时用懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.pageObj.total })
        // 转换数据格式，转成excel所需格式
        const data = this.formatJson(headers, rows)

        excel.export_json_to_excel({
          // 导出数据的表头
          header: Object.keys(headers),
          // 导出的具体数据
          data,
          // 导出的文件名
          filename: '员工信息表',
          // 单元格是否自适应宽度
          autoWidth: true,
          // 导出的文件类型
          bookType: 'xlsx'
        })
      })
    },
    // 将数组转化为二维数组的方法
    formatJson(headers, rows) {
      // 遍历数组
      // [{ username: '张三'},{},{}]  => [[’张三'],[],[]]
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 格式化日期
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    showQrCode(url) {
      if (url) {
        // dom更新（页面渲染）是异步的，所以使用nextTick保证点击后就出现弹窗
        this.showCodeDialog = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    },
    // 新增员工后跳转到新员工所在页面（最后一页）
    addEmployeeToPage() {
      this.pageObj.total++
      this.pageObj.page = Math.ceil(this.pageObj.total / this.pageObj.size)
      this.getEmployeeList()
    }
  }
}
</script>

<style>
.avator{
  object-fit: cover;
}
</style>
